import Vue from 'vue'
import VueRouter from 'vue-router'
import store from '@/store'

/* Layout */
import Login from '../pages/Login.vue'
import Dashboard from '../pages/dashboard'

Vue.use(VueRouter)

const routes = [
    { path: '', redirect: '/dashboard', hidden: true },
    { path: '/', redirect: '/dashboard', hidden: true },
    { path: '/login', component: Login },
    { path: '/dashboard', component: Dashboard }
]

const router = new VueRouter({
    routes
})

let isLogin = false

router.beforeEach((to, from, next) => {
    isLogin = store.state.authentication.token
    if (!isLogin) {
        console.log(to.path === '/login')
        if (to.path === '/login') {
            next()
        } else {
            next({ path: `/login?random=${Math.random()}` })
        }
    } else {
        // 已登录状态
        if (to.name === '/login' || to.name === '/' || to.name === '') {
            next({ path: '/dashboard' })
        } else {
            next()
        }
    }
})

export default router
